<template>
  <div class="import-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        excel导入

        <UploadExcel :on-success="handleSuccess" :before-upload="beforeUpload" />
      </el-card>
    </div>
  </div>
</template>

<script>
import { formatExcelDate } from '@/utils/index.js'
import { importEmployee } from '@/api/employees'
export default {
  name: 'ImportContainer',

  data() {
    return {

    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      console.log(results)
      console.log(header)

      const data = this.transExcel(results)
      console.log(data)
      // 3. 调用接口做上传
      this.doImport(data)
    },
    // 封装函数用于数据转换
    transExcel(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return results.map(item => {
        const obj = {}
        Object.keys(item).forEach(it => {
          if (mapInfo[it] === 'timeOfEntry' || mapInfo[it] === 'correctionTime') {
            // 后端需要的日期格式是标准时间 new Date一下
            obj[mapInfo[it]] = new Date(formatExcelDate(item[it]))
          } else {
            obj[mapInfo[it]] = item[it]
          }
        })
        return obj
      })
    },
    // 封装函数用于发ajax
    async doImport(data) {
      try {
        const res = await importEmployee(data)
        console.log('importEmployee', res)
        this.$message.success('导入成功')

        // 页面后退
        this.$router.back()
      } catch (err) {
        console.log('importEmployee', err)
        this.$message.error('导入失败')
      }
    }
  }
}
</script>

<style>

</style>
